import { editUserPhone } from 'admin/servers/servers';
import { Form, Input, message, Modal } from 'antd';

import React from 'react';
import { verifyPhone } from 'utils/tools';

interface Props {
  /**弹窗显示隐藏 */
  show: boolean;
  /**数据源 */
  record: Record<string, any>;
  /**成功回调 */
  sucessFn: () => void;
  /**关闭回调 */
  closeFn: () => void;
}

export const EditPhoneModal = (props: Props) => {
  const [form] = Form.useForm();
  const { show, record, sucessFn, closeFn } = props;
  const formLayout = {
    labelCol: { span: 10 },
    wrapperCol: { span: 12 },
  };

  /**表单提交 */
  const submit = () => {
    form.validateFields().then(async res => {
      const { mobile } = res;
      console.log('修改手机号**表单验证通过', mobile);
      try {
        await editUserPhone(record.userId, { mobile });
        message.success('手机号修改成功');
        sucessFn();
      } catch (error) {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      }
    });
  };
  /**弹窗关闭 */
  const cancel = () => {
    closeFn();
  };

  return (
    <Modal
      width={420}
      centered
      visible={show}
      title="修改手机号"
      onOk={submit}
      onCancel={cancel}
      destroyOnClose
    >
      <Form
        name="phoneForm"
        form={form}
        {...formLayout}
        initialValues={{
          oldPhone: record.mobile,
        }}
      >
        <Form.Item label="当前手机号" name="oldPhone">
          <Input disabled></Input>
        </Form.Item>
        <Form.Item
          label="新手机号"
          name="mobile"
          rules={verifyPhone}
          validateFirst={true}
          getValueFromEvent={event => {
            return event.target.value.replace(/[^0-9]+/g, '');
          }}
        >
          <Input maxLength={11} placeholder="请输入11位数字" />
        </Form.Item>
      </Form>
    </Modal>
  );
};
